<template>
  <div>
    <AdVxeModal
      v-bind="$attrs"
      :id="'ad-print-template-modal'"
      :title="t('component.print.printTemplate')"
      @register="register"
      @ok="handleOk"
      width="633px"
    >
      <!-- <AdVxeTable @register="registerTable" @cell-dbclick="cellDbclickEvent"> -->
      <AdVxeTable @register="registerTable" @cell-dbclick="cellDbclickEvent">
        <template #templateIdCol="{ row }">
          <vxe-button type="text" status="primary" @click="handleClick(row)">
            {{ row?.TemplateId }}
          </vxe-button>
        </template>
      </AdVxeTable>
    </AdVxeModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref } from 'vue';
  import { VxeButton } from 'vxe-table';
  import { AdVxeModal, useModalInner } from '@/components/AdVxeModal';
  import { AdVxeTable, useAdVxeTable, AdColumn, VxeGridDefines } from '@/components/AdVxeTable';

  import { useI18n } from '@/hooks/web/useI18n';
  import { isFunction } from '@/utils/is';

  import {
    PrintTemplateUserOutputDto,
    PrintTemplateUserDtoSimple,
  } from '@/api/report/admin/print/model';
  import { getPrintTemplatesByCode, setDefaultPrints } from '@/api/report/print';

  import { templateModalProps } from './props';

  defineOptions({ name: 'PrintTemplateModal' });
  const props = defineProps(templateModalProps);

  const { t } = useI18n();
  const printCodeRef = ref(props.printCode);

  // 模态窗体内部注册
  const [register, { closeModal, changeLoading, changeOkLoading }] = useModalInner(async (data) => {
    // console.log('useModalInner', data);
    changeLoading(true);
    try {
      if (data?.printCode !== undefined && data?.printCode !== null && data?.printCode !== '') {
        printCodeRef.value = data.printCode;
      }
      const dtos = await getTemplates();
      setTableData(dtos);
    } finally {
      changeLoading(false);
    }
  });

  const columns: AdColumn[] = [
    // #region 隐藏
    {
      title: t('entity.idTitle'),
      field: 'Id',
      resizable: true,
      width: 0,
      visible: false,
    },
    // #endregion
    {
      title: t('component.print.template.templateIdTitle'),
      field: 'TemplateId',
      resizable: true,
      width: 150,
      slots: { default: 'templateIdCol' },
    },
    {
      title: t('component.print.template.templateNameTitle'),
      field: 'TemplateName',
      resizable: true,
      width: 120,
    },
    // #region 隐藏
    {
      title: t('component.print.template.templateTypeTitle'),
      field: 'TemplateType',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.userIdTitle'),
      field: 'UserId',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.userNameTitle'),
      field: 'UserName',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.userNicknameTitle'),
      field: 'UserNickname',
      resizable: true,
      width: 0,
      visible: false,
    },
    // #endregion
    {
      title: '默认',
      field: 'IsDefault',
      resizable: true,
      width: 80,
      cellRender: {
        name: 'ASwitch',
        events: {
          change: async ({ row, data }) => {
            // console.log({ row, data });
            changeLoading(true);
            data.forEach((item) => {
              if (item.TemplateId !== row.TemplateId) {
                item.IsDefault = false;
              }
            });
            const isDefault = row.IsDefault;
            try {
              const result = await setDefaultTemplate({
                TemplateId: row.TemplateId,
                IsDefault: isDefault,
                OrderNo: 0,
              });
              if (result) {
                // row.IsDefault = isDefault;
                const dtos = await getTemplates();
                setTableData(dtos);
              }
            } finally {
              changeLoading(false);
            }
          },
        },
      },
      formatter: ({ cellValue }) => {
        return cellValue ? '是' : '否';
      },
    },
    // #region 隐藏
    {
      title: t('component.print.template.printIdTitle'),
      field: 'PrintId',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.printCodeTitle'),
      field: 'PrintCode',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.printNameTitle'),
      field: 'PrintName',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.userAsgnTitle'),
      field: 'UserAsgn',
      resizable: true,
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.orgAsgnTitle'),
      field: 'OrgAsgn',
      resizable: true,
      width: 0,
      visible: false,
    },
    // #endregion
    {
      title: t('component.print.template.commentsTitle'),
      field: 'Comments',
      resizable: true,
      width: 160,
    },
    // #region 隐藏
    {
      title: t('component.print.template.logEnabledTitle'),
      field: 'LogEnabled',
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.enabledTitle'),
      field: 'Enabled',
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.enableFromTitle'),
      field: 'EnableFrom',
      width: 0,
      visible: false,
    },
    {
      title: t('component.print.template.enableToTitle'),
      field: 'EnableTo',
      width: 0,
      visible: false,
    },
    {
      title: t('entity.creationAudited.creatorIdTitle'),
      field: 'CreatorId',
      width: 0,
      visible: false,
    },
    {
      title: t('entity.creationAudited.createdTimeTitle'),
      field: 'CreatedTime',
      width: 0,
      visible: false,
    },
    {
      title: t('entity.updateAudited.updaterIdTitle'),
      field: 'UpdaterId',
      width: 0,
      visible: false,
    },
    {
      title: t('entity.updateAudited.updatedTimeTitle'),
      field: 'UpdatedTime',
      width: 0,
      visible: false,
    },
    // #endregion
  ];

  // 表格注册
  const [registerTable, { getTable, setData: setTableData }] = useAdVxeTable({
    id: 'ad-print-template-modal-table',
    // title: t('component.print.template.printTemplateList'),
    title: undefined,
    columns,
    size: 'small', // 表格大小
    border: 'outer', // default（默认）, full（完整边框）, outer（外边框）, inner（内边框）, none（无边框）
    showSeqColumn: false, // 是否显示序号列
    stripe: true, // 斑马纹
    toolbarConfig: { enabled: false }, // 工具栏信息配置
    pagerConfig: { enabled: false }, // 分页信息配置
    clickToSelect: true, // 点击行是否选中 checkbox 或者 radio。
    selection: 'radio',
  });

  //#region 获取模板集合
  /**
   * 获取模板集合
   * @returns 打印模板用户输出DTO集合
   */
  async function getTemplates(): Promise<PrintTemplateUserOutputDto[]> {
    const getTemplatesApi = props.getTemplatesApi;
    if (getTemplatesApi && isFunction(getTemplatesApi)) {
      return await getTemplatesApi(printCodeRef.value);
    } else {
      const result = await getPrintTemplatesByCode(printCodeRef.value);
      if (result?.Type === 200) {
        return result.Data as PrintTemplateUserOutputDto[];
      }
      return [];
    }
  }
  //#endregion
  //#region 设置默认打印模板
  /**
   * 设置默认打印模板
   * @param dtos 打印模板用户简单DTO集合
   */
  async function setDefaultTemplate(dtos: PrintTemplateUserDtoSimple): Promise<boolean> {
    const setDefaultTemplateApi = props.setDefaultTemplateApi;
    if (setDefaultTemplateApi && isFunction(setDefaultTemplateApi)) {
      return await setDefaultTemplateApi([dtos]);
    } else {
      const result = await setDefaultPrints([dtos]);
      return result?.Type === 200;
    }
  }
  //#endregion

  /** 单元格被双击时会触发该事件 */
  async function cellDbclickEvent(e: VxeGridDefines.CellDblclickEventParams) {
    await emitSelect(e?.row);
  }

  /** 处理点击 */
  async function handleClick(row: Recordable) {
    await emitSelect(row);
  }

  /** 处理确定按钮 */
  async function handleOk() {
    const table = getTable();
    const row = table?.getRadioRecord();
    await emitSelect(row);
  }

  /** 触发数据选择事件 */
  async function emitSelect(record: Recordable) {
    changeOkLoading(true);
    try {
      // console.log('点击了', record);
      if (record?.TemplateId) {
        const executePrintApi = props.executePrintApi;
        if (executePrintApi && isFunction(executePrintApi)) {
          await executePrintApi(record.TemplateId);
        }
        closeModal();
      }
    } finally {
      changeOkLoading(false);
    }
  }
</script>
